import React, { Component } from 'react';
import { View, Text, StyleSheet, ScrollView, Dimensions, Image, RefreshControl,Platform } from 'react-native';
import constants from '../../../utils/constants';
import { Flex, Icon } from 'antd-mobile-rn';
import { Echarts, echarts } from 'react-native-secharts';
import moment from 'moment';
import { BoxShadow } from 'react-native-shadow';
import ReportCalendar from '../../../components/reportCalendar';
import Utils from '../../../utils';
import api from '../../../utils/api';
// import { VictoryChart, VictoryBar } from "victory-native";

const window = Dimensions.get("window");
const screen = Dimensions.get("screen");


const getDate = (date) => {
    const momentDate = moment(date);
    return {
        startDate: momentDate.startOf("month").format("YYYY-MM-DD"),
        endDate: momentDate.endOf("month").format("YYYY-MM-DD")
    }
}


//颜色对象
const randomColor = () => {
    const colors = [
        "#191E47",
        "#00B7A5",
        "#FDD495",
        "#FCCF87",
        "#FBBF62",
        "#FBBB58",
        "#85879D",
        "#555977",
        "#353A5E",
        "#34395D"
    ]
    return colors[parseInt(Math.random() * colors.length)];
}



const styles = StyleSheet.create({
    boxStyle: {
        flex: 1,
        backgroundColor: "#fff",
        padding: 15,
        borderRadius: 10,
        borderWidth: 1,
        marginBottom: 20,
        borderColor: Platform.OS === "ios"?"rgba(0,0,0,0.1)":"rgba(0,0,0,0.01)",
        elevation: 5,
        shadowColor:"#000",
        shadowOffset:{
            shadowOffsetX:5
        },
        shadowOpacity:0.2,
        shadowRadius:10
    }
})


export default class Report extends Component {

    static navigationOptions = (e) => {
        return {
            title: "学习报告",
            tabBarOnPress: (screen) => {
                const { defaultHandler, navigation } = screen;

                console.log("Study-Report :", screen);

                const loadData = navigation.getParam("loadData", () => { });

                loadData();

                defaultHandler();
            }

        }
    }

    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            apple: [2, 4, 7, 2, 2, 7, 13, 16],
            organ: [6, 9, 9, 2, 8, 7, 17, 18],
            uri: "",
            user: {},
            studyTime: {
                remainTimes: 0,
                total: 0,
                week: 0,
                today: 0
            },
            lastWeek: {
                loading: true,
                data: {
                    x: [],
                    y: []
                }
            },
            timeDistribut: {
                loading: true,
                data: []
            },
            learnProcess: {
                loading: true,
                data: []
            },
            signHistory: {
                loading: true,
                data: {},
                date: new Date()
            },
            isLoadData: false
        };

        const { navigation } = this.props;

        navigation.setParams({
            loadData: () => {
                //获取用户信息
                Utils.getLoginInfo().then(user => {
                    this.setState({
                        user: user ? user : {}
                    })
                });

                if (!this.state.isLoadData) {
                    //加载数据
                    this.loadData();
                    this.setState({
                        isLoadData: true
                    })
                }


            }
        });


    }

    /**
     * 加载最近7天数据
     */
    loadLastWeekData = () => {
        const { lastWeek } = this.state;
        lastWeek.loading = true;
        this.setState({
            lastWeek: lastWeek
        });
        api({
            url: "/studinReport/data-statistics/lastWeek",
            method: "POST"
        }).then(data => {

            lastWeek.loading = false;
            if (!data.success) {
                this.setState({
                    lastWeek: lastWeek
                })
                return;
            }
            const ret = data.result.barVo.datas;
            const keys = Object.keys(ret);
            lastWeek.data = {
                x: keys,
                y: keys.map(key => { return ret[key] })
            }


            this.setState({
                lastWeek: lastWeek
            })


        }).catch(() => {
            lastWeek.loading = false;
            this.setState({
                lastWeek: lastWeek
            });
        })
    }

    /**
     * 时间分配
     */
    loadTimeDistribut = () => {
        const { timeDistribut } = this.state;
        api({
            url: "/studinReport/data-statistics/timeDistribut",
            method: "POST"
        }).then(data => {
            timeDistribut.loading = false
            if (!data.success) {
                this.setState({
                    timeDistribut: timeDistribut
                })
                return;
            }
            const ret = data.result.tableVos;
            timeDistribut.data = ret.map(item => {
                item.color = randomColor();
                return item;
            });

            this.setState({
                timeDistribut: timeDistribut
            })
        }).catch(data => {
            timeDistribut.loading = false;
            this.setState({
                timeDistribut: timeDistribut
            });
        })
    }


    /**
     * 学习进度
     */
    loadlearnProcess = () => {
        const { learnProcess } = this.state;
        api({
            url: "/studinReport/data-statistics/learnProcess",
            method: "POST"
        }).then(data => {
            learnProcess.loading = false
            if (!data.success) {
                this.setState({
                    learnProcess: learnProcess
                })
                return;
            }
            const ret = data.result.tableVos;
            learnProcess.data = ret;
            this.setState({
                learnProcess: learnProcess
            })
        }).catch(data => {
            learnProcess.loading = false;
            this.setState({
                learnProcess: learnProcess
            });
        })
    }


    loadSignHistory = (param) => {
        const { signHistory } = this.state;
        api({
            url: "/studinReport/data-statistics/signHistory",
            method: "POST",
            body: param
        }).then(data => {
            signHistory.loading = false
            if (!data.success) {
                this.setState({
                    signHistory: signHistory
                })
                return;
            }
            const ret = data.result.dateVos;

            signHistory.data = {};

            ret.forEach(item => {
                const key = moment(item.taskDate).format("YYYYMMDD");
                signHistory.data[key] = item;
            });

            this.setState({
                signHistory: signHistory
            })
        }).catch(data => {
            signHistory.loading = false;
            this.setState({
                signHistory: signHistory
            });
        })
    }

    loadData = () => {

        api({
            url: "/studinReport/data-statistics/top",
            method: "POST"
        }).then(data => {
            this.setState({
                refreshing: false,
                studyTime: data.result ? data.result : this.state.studyTime
            })
        }).catch(() => {

        })

        //加载最近7天的数据
        this.loadLastWeekData();
        //时间分配
        this.loadTimeDistribut();
        //学习进度
        this.loadlearnProcess();
        //打卡记录
        this.loadSignHistory(getDate(this.state.signHistory.date));

    }

    componentDidMount() {







    }

    onpress = () => {



    }

    render() {

        const { user, studyTime, lastWeek, timeDistribut, learnProcess, signHistory } = this.state;

        console.log("lastWeek", lastWeek);



        const timeOptions = {
            tooltip: {
                trigger: 'item',
                position: [10, 0],
                textStyle: {
                    fontSize: 10
                },
                formatter: "{b} : {d}%"

            },
            color: timeDistribut.data.map(item => item.color),
            series: [
                {
                    type: 'pie',
                    radius: '55%',
                    center: ['40%', '50%'],
                    data: timeDistribut.data.map(item => {
                        return {
                            name: item.taskName,
                            value: parseFloat(item.spend),
                            percent: item.percent
                        }
                    }),
                    legendHoverLink: false,
                    itemStyle: {
                        normal: {
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            }
                        },
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)',

                        }
                    }
                }
            ]
        };



        return (

            <ScrollView refreshControl={
                <RefreshControl
                    colors={[constants.themeColor]}
                    refreshing={this.state.refreshing}
                    onRefresh={() => {
                        this.setState({
                            refreshing: true
                        })
                        this.loadData();
                        setTimeout(() => {
                            this.setState({
                                refreshing: false
                            });
                        }, 3000)
                    }}
                    progressBackgroundColor="#fff"

                />
            } ref="full" >
                <View style={{ padding: 20 }} >
                    <View style={{ alignItems: "center", marginBottom: 20 }}>
                        <Text style={{ fontSize: 24, color: constants.themeColor }} onPress={this.onpress} >{user.name}的学习报告</Text>
                        <View style={{ width: 100, height: 3, backgroundColor: constants.themeColor, marginTop: 10 }}></View>
                    </View>



                    <View style={styles.boxStyle} >
                        <View>
                            <Text style={{ color: constants.themeColor, fontSize: 16 }}>学习时间</Text>
                        </View>
                        <Flex>
                            <Flex.Item>
                                <View style={{ alignItems: "center" }}>
                                    <Text style={{ fontSize: 16, paddingTop: 20 }}>累计学习</Text>
                                </View>
                                <View style={{ justifyContent: "center", alignItems: "center", flexDirection: "row" }}>
                                    <Text style={{ fontSize: 60, color: "#FBB03B" }}>{studyTime.total}</Text>
                                    <Text style={{ fontSize: 16, marginTop: 30, color: "#000", marginLeft: 5 }}>小时</Text>
                                </View>
                            </Flex.Item>
                            <Flex.Item>
                                <View style={{ flexDirection: "row", marginBottom: 15, paddingTop: 20 }}>
                                    <Text style={{ fontSize: 16, width: 80, textAlign: "right" }}>今日</Text>
                                    <Text style={{ fontSize: 16, width: 40, textAlign: "center", color: "#000", fontWeight: "bold" }}>{studyTime.today}</Text>
                                    <Text style={{ fontSize: 16 }}>小时</Text>
                                </View>
                                <View style={{ flexDirection: "row", marginBottom: 15 }}>
                                    <Text style={{ fontSize: 16, width: 80, textAlign: "right" }}>本周</Text>
                                    <Text style={{ fontSize: 16, width: 40, textAlign: "center", color: "#000", fontWeight: "bold" }}>{studyTime.week}</Text>
                                    <Text style={{ fontSize: 16, width: 80 }}>小时</Text>
                                </View>
                                <View style={{ flexDirection: "row", marginBottom: 15 }}>
                                    <Text style={{ fontSize: 16, width: 80, textAlign: "right" }}>连续打卡</Text>
                                    <Text style={{ fontSize: 16, width: 40, textAlign: "center", color: "#000", fontWeight: "bold" }}>{studyTime.remainTimes}</Text>
                                    <Text style={{ fontSize: 16 }}>天</Text>
                                </View>
                            </Flex.Item>
                        </Flex>
                    </View>


                    <View style={styles.boxStyle}>
                        <View>
                            <Text style={{ color: constants.themeColor, fontSize: 16 }}>近一周时间概况</Text>
                        </View>
                        <View style={{ flex: 1, overflow: "hidden" }}>
                            <Echarts option={{
                                tooltip: {
                                    trigger: 'item',
                                    textStyle: {
                                        fontSize: 10
                                    }

                                },
                                grid: {
                                    top: "40",
                                    left: "0",
                                    containLabel: true
                                },
                                xAxis: [
                                    {
                                        type: 'category',
                                        data: lastWeek.data.x,
                                        axisLabel: {
                                            interval: 0,
                                            rotate: 30
                                        }
                                    }
                                ],
                                yAxis: [
                                    {
                                        type: 'value'
                                    }
                                ],
                                //图形的颜色组
                                color: ['rgb(130,132,154)'],
                                //需要显示的图形名称，类型，以及数据设置
                                series: [
                                    {
                                        //默认显
                                        type: 'bar',
                                        data: lastWeek.data.y,
                                        barWidth: 20

                                    }
                                ]
                            }} width={window.width - 50} height={250} />
                        </View>
                    </View>


                    <View style={styles.boxStyle}>
                        <View>
                            <Text style={{ color: constants.themeColor, fontSize: 16 }}>时间分配</Text>
                        </View>
                        <Flex>
                            <Flex.Item>
                                <View style={{
                                    flex: 1, overflow: "hidden", alignItems: "center", justifyContent: 'center',
                                    textAlignVertical: 'center',
                                }}>
                                    <Echarts width={window.width / 2 - 20} height={220} option={timeOptions} />
                                </View>
                            </Flex.Item>
                            <Flex.Item>
                                {/* <ScrollView> */}
                                <View style={{ width: window.width / 2 - 20, paddingTop: 20, paddingBottom: 2 }}>
                                    {
                                        timeDistribut.data.map((item, index) => {
                                            return (
                                                <Flex key={index} style={{ marginBottom: 10 }}>
                                                    <Flex.Item>
                                                        <Flex>
                                                            <Flex.Item>
                                                                <View style={{ flexDirection: "row" }}>
                                                                    <View>
                                                                        <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: item.color, marginTop: 6 }}></View>
                                                                    </View>

                                                                    <Text style={{ marginLeft: 5 }}>{item.taskName} {item.percent}</Text>
                                                                </View>


                                                            </Flex.Item>
                                                            <Flex.Item style={{ alignItems: "center" }}>
                                                                <Text style={{ marginLeft: 10 }} >{item.spend}</Text>
                                                            </Flex.Item>

                                                        </Flex>
                                                    </Flex.Item>
                                                </Flex>
                                            )
                                        })
                                    }

                                </View>
                                {/* </ScrollView> */}
                            </Flex.Item>
                        </Flex>


                    </View>
                    {/* </BoxShadow> */}
                    {/* <BoxShadow setting={{
                        width: (screen.width - 40), //包裹的子内容多宽这里必须多宽
                        height: 180,//同上

                        border: 15,//阴影宽度
                        radius: 15,//包裹的子元素圆角多少这里必须是多少
                        opacity: 0.2,//透明度
                        x: 0,
                        y: 8,
                        style: {
                            marginBottom: 20,



                        }
                    }}> */}
                    <View style={styles.boxStyle}>
                        <View style={{ marginBottom: 5 }}>
                            <Text style={{ color: constants.themeColor, fontSize: 16 }}>学习任务进度</Text>
                        </View>
                        {/* <ScrollView> */}
                        <View style={{ padding: 5 }} >

                            {
                                learnProcess.data.map((item, index) => {
                                    return (
                                        <View key={index} style={{ flexDirection: "row", flex: 1, marginBottom: 10 }}>
                                            <View style={{ width: "20%", padding: 5 }}>
                                                <Text style={{ fontSize: 18, marginTop: 2 }}>{item.taskName}</Text>
                                            </View>
                                            <View style={{ width: "60%", padding: 5 }}>
                                                <Text style={{ color: "#505050", fontSize: 14 }}>{moment(item.startDate).format("YYYY.MM.DD")} ~ {moment(item.endDate).format("YYYY.MM.DD")}</Text>
                                                <Text style={{ color: "#505050" }}>{item.remainWeek}</Text>
                                            </View>
                                            <View style={{ width: "20%", padding: 5, alignContent: "flex-end" }}>
                                                <Text style={{ color: "#505050", fontSize: 14, marginBottom: 5 }}>{item.completedCount}/{item.total}</Text>
                                                <View style={{ width: "100%", height: 5, backgroundColor: "#ccc" }}>
                                                    <View style={{ width: item.completedCount > 0 ? (item.completedCount / item.total) * 100 + "%" : 0, height: 5, backgroundColor: constants.themeColor }}>

                                                    </View>
                                                </View>
                                            </View>
                                        </View>
                                    )
                                })
                            }

                        </View>
                    </View>
                    <View style={styles.boxStyle}>
                        <View style={{ marginBottom: 10 }}>
                            <Text style={{ color: constants.themeColor, fontSize: 16 }}>我的打卡日历</Text>
                        </View>
                        <View>
                            <ReportCalendar onCalendarChange={(date) => {
                                signHistory.date = date;
                                this.setState({
                                    signHistory: signHistory
                                })
                                this.loadSignHistory(getDate(date));

                            }} date={signHistory.date} itemStyle={(d) => {
                                if(!d){
                                    return;
                                }
                                const dateKey = moment(d).format("YYYYMMDD");
                                const nowDate = moment(new Date()).format("YYYYMMDD");
                                if (dateKey === nowDate) {
                                    return {
                                        backgroundColor: "#FCC062",
                                        borderColor: "#FCC062"
                                    }
                                }
                                const item = signHistory.data[dateKey];
                                if (item) {
                                    if (item.isCompleted === 2) {
                                        return {
                                            backgroundColor: "#A5A6B4",
                                            borderColor: "#A5A6B4"
                                        }
                                    }
                                    if (item.isCompleted === 1) {
                                        return {
                                            backgroundColor: "#4B4D69",
                                            borderColor: "#4B4D69"
                                        }
                                    }
                                }

                                return {};
                            }} />
                        </View>
                    </View>
                </View>
            </ScrollView>

        )
    }
}